package org.crazyit.app.action;

import java.sql.SQLException;
import java.util.Date;

import javax.servlet.http.Cookie;

import org.apache.struts2.ServletActionContext;
import org.crazyit.app.exception.MyException;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.interceptor.PreResultListener;

public class LoginRegistAction extends ActionSupport {
	private String username;
	private String password;
	private String tip;

	public String regist() throws Exception {
		ActionContext.getContext().getSession().put("user", getUsername());
		setTip("恭喜您，" + getUsername() + "，您已经注册成功！");
		return SUCCESS;
	}

	public String execute() throws Exception {
		if (getUsername().equals("bm") && getPassword().equals("123")) {
			ActionContext.getContext().getSession().put("user", getUsername());
			setTip("欢迎，" + getUsername() + "，您已经登录成功！");
			return SUCCESS;
		} else {
			return ERROR;
		}
	}

	public String login() throws Exception {
		ActionInvocation invocation = ActionContext.getContext()
				.getActionInvocation();
		invocation.addPreResultListener(new PreResultListener() {
			@Override
			public void beforeResult(ActionInvocation invocation,
					String resultCode) {
				System.out.println("返回的逻辑视图名字为：" + resultCode);
				invocation.getInvocationContext().put("extra",
						new Date() + "由" + resultCode + "逻辑视图名转入");
			}
		});
		ActionContext ctx = ActionContext.getContext();
		Integer counter = (Integer) ctx.getApplication().get("counter");
		if (counter == null) {
			counter = 1;
		} else {
			counter = counter + 1;
		}
		ctx.getApplication().put("counter", counter);
		if (getUsername().equalsIgnoreCase("user")) {
			throw new MyException("自定义异常");
		}
		if (getUsername().equalsIgnoreCase("sql")) {
			throw new SQLException("用户名不能为SQL");
		}
		if (getUsername().equals("bm") && getPassword().equals("123")) {
			ActionContext.getContext().getSession().put("user", getUsername());
			// 通过response添加Cookie
			Cookie cookie2 = new Cookie("user2", getUsername());
			cookie2.setMaxAge(60 * 60);
			ServletActionContext.getResponse().addCookie(cookie2);
			ctx.put("tip", "服务器提示：您已经成功登录");
			return SUCCESS;
		} else {
			return ERROR;
		}
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getTip() {
		return tip;
	}

	public void setTip(String tip) {
		this.tip = tip;
	}
}
